using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using HslCommunicationEx.OpcUa.Server;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using MQTTnet.AspNetCore;
using Opc.Ua;
using Catastrophe.Initialize;
using Catastrophe.Log;

namespace Catastrophe.BasePC.UI.SystemIni
{
	public static class ServiceStart
	{
		public static Task WebApiStart<T>(int httpPort = 1812, int? mqttTcpPort = null, bool useMqtt = false, string mqttUser = "admin", string mqttPwd = "123") where T : class
		{
			IConfigurationRoot config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
			{
				{
					"UseMqtt",
					useMqtt.ToString()
				},
				{ "MqttUser", mqttUser },
				{ "MqttPwd", mqttPwd }
			}).Build();
			IHostBuilder hostBuilder = Host.CreateDefaultBuilder(Array.Empty<string>()).ConfigureWebHostDefaults(delegate(IWebHostBuilder webBuilder)
			{
				webBuilder.UseConfiguration(config).UseKestrel(delegate(KestrelServerOptions o)
				{
					if (mqttTcpPort.HasValue)
					{
						o.ListenAnyIP(mqttTcpPort.Value, delegate(ListenOptions l)
						{
							l.UseMqtt();
						});
					}
					o.ListenAnyIP(httpPort);
				});
				webBuilder.UseStartup<T>();
			});
			return hostBuilder.RunConsoleAsync();
		}

		public static void StartOpcUaService<T>(int port = 4810, string nameSpace = "SYTLTechnology", string userName = "", string pwd = "") where T : HslCommunicationEx.OpcUa.Server.PeanutOpcUaNodeManager
        {
			Task.Run(delegate
			{
				try
				{
                    PeanutOpcUaManager<T> CdcatastropheOpcUaManager = new PeanutOpcUaManager<T>();
					UserTokenType userTokenType = UserTokenType.Anonymous;
					if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(pwd))
					{
						userTokenType = UserTokenType.UserName;
						CdcatastropheOpcUaManager.CusOpcServer.AddUser(userName, pwd);
					}
					if (!string.IsNullOrWhiteSpace(nameSpace))
					{
						CdcatastropheOpcUaManager.CusOpcServer.NameSpace = nameSpace;
					}
					Tuple<bool, string> tuple = CdcatastropheOpcUaManager.CreateServerInstance(Environment.MachineName, port, userTokenType);
					CdcatastropheOpcUaManager.CusOpcServer.NameSpace = nameSpace;
				}
				catch (Exception ex)
				{
					LogSession.Ifile.WriteLogNormal(LogLevelEnum.Error, "Start OpcUa Server Failed!", ex, FrameEnvironment.UserName, "StartOpcUaService", "D:\\Csharp\\CdcatastropheNet6.0\\Catastrophe.BasePC.UI\\Catastrophe.BasePC.UI\\SystemIni\\ServiceStart.cs", 98);
				}
			});
		}
	}
}
